package cn.lhl.web.controller.system;

import cn.lhl.domain.system.Dept;
import cn.lhl.service.system.DeptService;
import cn.lhl.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list", name = "部门列表分页版")
    //分页列表需要两个参数(页面显示几行数据size,第几页page)
    public String list(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size) {
        //调用Service得到PageInfo
        PageInfo pageInfo = deptService.findAll(page, size, companyId);//BaseController中有companyId
        model.addAttribute("page", pageInfo);
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "去新增界面")
    //新增字段需要查找所有的部门字段
    public String toAdd(){
        //该界面需要获得全部的部门列表所以需要调用数据库查询
        List<Dept> deptList = deptService.deptList(companyId);
        model.addAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    //注意修改和保存用的是一个界面所以需要判断dept_id字段是否为空
    @RequestMapping(value = "/edit",name = "新建或修改")
    public String edit(Dept dept){//Dept哪来的?
        //先给两个字段赋值
        dept.setCompanyId(companyId);
        dept.setCompanyName(companyName);
        if(StringUtil.isEmpty(dept.getId())){
            //新建,生成UUid
            dept.setId(UUID.randomUUID().toString());
            //调用方法保存
            deptService.save(dept);
        }else {
            //更新
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "去修改页面")
    public String toUpdate(String id){
        //需要携带数据,从数据库中根据部门id查询得出
        Dept dept = deptService.findById(id);
        //此页面同样需要将所有部门列表查询出来
        List<Dept> deptList = deptService.deptList(companyId);
        model.addAttribute("dept",dept);
        model.addAttribute("deptList",deptList);
        return "/system/dept/dept-update";
    }

    @RequestMapping(value = "/delete" ,name = "根据id删除部门")
    public String delete(String id){
        deptService.delete(id);
        return "redirect:/system/dept/list.do";
    }
}
